import * as THREE from 'three';
import Stats from 'three/addons/libs/stats.module.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
export function CreateThree(options) {
  const stats = new Stats();
  const scene = new THREE.Scene();
  if (options?.scene) {
    for (const key in options.scene) {
      scene[key] = options.scene[key];
    }
  }
  // aspect
  const { aspect, width, height, pixelRatio } = windowAspect();
  // renderer
  const renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.toneMapping = THREE.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 0.85;
  renderer.setPixelRatio(pixelRatio);
  renderer.setSize(width, height);

  const camera = new THREE.PerspectiveCamera(45, aspect, 1, 200000);
  if (options?.camera) {
    for (const key in options.camera) {
      if (typeof options.camera[key] === 'object') {
        for (const k in options.camera[key]) {
          camera[key][k] = options.camera[key][k];
        }
      } else {
        camera[key] = options.camera[key];
      }
    }
  }

  const control = new OrbitControls(camera, renderer.domElement);
  if (options?.control) {
    for (const key in options.control) {
      control[key] = options.control[key];
    }
  }
  const bind = el => {
    const dom = document.querySelector(el);
    dom.appendChild(renderer.domElement);
    if (stats) {
      dom.appendChild(stats.dom);
    }
    window.addEventListener('resize', onResize, false);
  };

  const onResize = () => {
    const { innerWidth, innerHeight } = window;
    camera.aspect = innerWidth / innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(innerWidth, innerHeight);
  };

  return { stats, scene, camera, renderer, control, bind };
}
function windowAspect() {
  return {
    width: window.innerWidth,
    height: window.innerHeight,
    pixelRatio: window.devicePixelRatio,
    aspect: window.innerWidth / window.innerHeight
  };
}
